package com.example.albumhot;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import android.R.bool;
import android.app.*;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity {
	private ProgressDialog pDialog;

	JSONObject jsonobject;
	JSONArray jsonarray;
	ListView lv;
	ProgressDialog mProgressDialog;
	ArrayList<HashMap<String, String>> arraylist;
	static String ID = "id";
	SimpleAdapter adapter;
	private Context mCon;
	static String ARTIST = "artist";
	static String TITLE = "title";
	private static String url = "http://service2.topprinter.org/album-rest";
	final int CONTEXT_MENU_DELETE = 1;
	final int CONTEXT_MENU_RENAME = 2;
	final int CONTEXT_MENU_SORT = 3;
	final int CONTEXT_MENU_ADD = 4;
	final int CONTEXT_MENU_INSERT = 5;
	HashMap<String, String> resultp = new HashMap<String, String>();
	Menu mymenu;
	private MenuItem refreshMenuItem;
	private ActionBar actionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String id1 = ((TextView) view.findViewById(R.id.id)).getText()
						.toString();
				String artist = ((TextView) view.findViewById(R.id.artist))
						.getText().toString();
				String title = ((TextView) view.findViewById(R.id.title))
						.getText().toString();
				Intent in = new Intent(getApplicationContext(),
						ItemChildsAlbum.class);
				in.putExtra(ID, id1);
				in.putExtra(ARTIST, artist);
				in.putExtra(TITLE, title);
				startActivity(in);

			}
		});
		actionBar = getActionBar();
		registerForContextMenu(lv);
		new GetURL().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh:
			refreshMenuItem = item;
			new GetURL().execute();
			new Loaddata().execute();
			return true;
		case R.id.action_settings:

			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");
		menu.add(Menu.NONE, CONTEXT_MENU_RENAME, Menu.NONE, "Rename");
		menu.add(Menu.NONE, CONTEXT_MENU_ADD, Menu.NONE, "Add");
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AsyncHttpClient client = new AsyncHttpClient();
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		Long id = lv.getAdapter().getItemId(info.position);
		resultp = arraylist.get(Integer.valueOf(id.intValue()));
		final int number_of_item_in_listview = Integer.valueOf(id.intValue());
		switch (item.getItemId()) {
		case CONTEXT_MENU_DELETE:
			Toast.makeText(
					this,
					"You removed item " + resultp.get(MainActivity.ID)
							+ " from the list", Toast.LENGTH_SHORT).show();
			client.delete("http://service2.topprinter.org/album-rest/"
					+ resultp.get(MainActivity.ID),
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(String response) {
							Log.i("thanh cong", response + ":"
									+ number_of_item_in_listview);
						}

						@Override
						public void onFailure(Throwable e, String response) {
							Log.i("onFailure", response);
						}
					});

			arraylist.remove(number_of_item_in_listview);
			adapter.notifyDataSetChanged();

			return (true);

		case CONTEXT_MENU_RENAME:
			LayoutInflater layoutInflater = LayoutInflater.from(this);
			View promptView = layoutInflater.inflate(R.layout.alertbox, null);
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Rename Artist Album");
			final EditText editID = (EditText) promptView
					.findViewById(R.id.edtID);
			editID.setText(resultp.get(MainActivity.ID));
			editID.setEnabled(false);
			final EditText editARTIST = (EditText) promptView
					.findViewById(R.id.edtARTIST);
			final EditText editTITLE = (EditText) promptView
					.findViewById(R.id.edtTITLE);
			alert.setView(promptView);
			alert.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							HashMap<String, String> paramMap = new HashMap<String, String>();
							paramMap.put("id", editID.getText().toString());
							paramMap.put("artist", editARTIST.getText()
									.toString());
							paramMap.put("title", editTITLE.getText()
									.toString());
							RequestParams params = new RequestParams(paramMap);
							// params.put("id", "20");
							// params.put("artist", "bbb");
							// params.put("title", "ccc");
							Log.i("params", "before:" + params);
							client.post(url, params,
									new AsyncHttpResponseHandler() {
										@Override
										public void onSuccess(String response) {
											Log.i("onSuccess",
													"resultp: "
															+ resultp
																	.get(MainActivity.ID));
											Log.i("onSuccess", "response: "
													+ response);
										}

										@Override
										public void onFailure(Throwable error,
												String content) {
											Log.i("onFailure", content);
										}
									});
							Log.i("params", "after:" + params);
							arraylist.set(number_of_item_in_listview, paramMap);
							adapter.notifyDataSetChanged();
						}
					});
			alert.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {

						}
					});

			alert.show();
			return (true);
		case CONTEXT_MENU_ADD:
			LayoutInflater layoutInflaterAdd = LayoutInflater.from(this);
			View promptViewAdd = layoutInflaterAdd.inflate(R.layout.addbox,
					null);
			AlertDialog.Builder alertAdd = new AlertDialog.Builder(this);
			final EditText addARTIST = (EditText) promptViewAdd
					.findViewById(R.id.iedtartist);
			final EditText addTITLE = (EditText) promptViewAdd
					.findViewById(R.id.iedttitle);
			alertAdd.setView(promptViewAdd);
			alertAdd.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// Log.e("value", "" + value);
							HashMap<String, String> paramMap = new HashMap<String, String>();
							paramMap.put("id", "0");
							paramMap.put("artist", addARTIST.getText()
									.toString());
							paramMap.put("title", addTITLE.getText().toString());
							RequestParams params = new RequestParams(paramMap);
							Log.i("params", "before:" + params);
							client.post(url, params,
									new AsyncHttpResponseHandler() {
										@Override
										public void onSuccess(String response) {
											Log.i("onSuccess", "response: "
													+ response);
										}

										@Override
										public void onFailure(Throwable error,
												String content) {
											Log.i("onFailure", content);
										}
									});
							Log.i("params", "after:" + params);
							// arraylist.set(number_of_item_in_listview,
							// paramMap);

							adapter.notifyDataSetChanged();
						}
					});
			alertAdd.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {

						}
					});

			alertAdd.show();
			return (true);
		}
		return (super.onOptionsItemSelected(item));
	}

	private class Loaddata extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			refreshMenuItem.setActionView(R.layout.progressbar);
			refreshMenuItem.expandActionView();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			refreshMenuItem.collapseActionView();
			refreshMenuItem.setActionView(null);
		}
	};

	private class GetURL extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			arraylist = new ArrayList<HashMap<String, String>>();
			ServiceHandler sh = new ServiceHandler();
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
			// Log.i("path url", jsonStr);
			try {
				JSONObject jsonObj = new JSONObject(jsonStr);
				jsonarray = jsonObj.getJSONArray("data");
				for (int i = 0; i < jsonarray.length(); i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					jsonobject = jsonarray.getJSONObject(i);
					map.put("id", jsonobject.getString("id"));
					map.put("artist", jsonobject.getString("artist"));
					map.put("title", jsonobject.getString("title"));

					arraylist.add(map);
				}
			} catch (JSONException e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing())
				pDialog.dismiss();
			adapter = new SimpleAdapter(MainActivity.this, arraylist,
					R.layout.list_item, new String[] { ID, ARTIST, TITLE },
					new int[] { R.id.id, R.id.artist, R.id.title });
			setListAdapter(adapter);
		}

	}

}
